package com.zidongxiangxi.clock.server.message.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zidongxiangxi.clock.http.constants.RabbitConstant;
import com.zidongxiangxi.clock.http.message.ClockMessage;
import com.zidongxiangxi.clock.server.message.handler.AbstractClockMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @author chenxudong
 * @date 2021/02/01
 */
@Slf4j
@Component
public class ClockMessageListener {
    private final List<AbstractClockMessageHandler> handlers;

    private final static Type EVENT_STRING_TYPE = (new TypeReference<ClockMessage<String>>() {
    }).getType();

    public ClockMessageListener(List<AbstractClockMessageHandler> handlers) {
        this.handlers = handlers;
    }

    @RabbitListener(queues = RabbitConstant.CLOCK_TASK_QUEUE)
    public void handleMessage(byte[] message) {
        ClockMessage<String> clockMessage = JSON.parseObject(new String(message), EVENT_STRING_TYPE);
        log.info("receive message, message = {}", JSON.toJSONString(clockMessage));
        try {
            handlers.forEach(handler -> {
                if (handler.canHandle(clockMessage)) {
                    handler.handle(clockMessage);
                }
                log.info("success to handle message! message = {}",
                    JSON.toJSONString(clockMessage));
            });
        } catch (Exception e) {
            log.error("fail to handle message! message = {}",
                JSON.toJSONString(clockMessage));
        }
    }
}
